package org.glavo.bot

import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.io.File
import java.util.concurrent.CopyOnWriteArraySet

object ChatOffList {
    private val chatListFile = File("ChatList.txt")

    private val mutex = Mutex()

    val list: CopyOnWriteArraySet<Long> =
        if (chatListFile.exists()) {
            CopyOnWriteArraySet(chatListFile.readLines().mapNotNull { it.toLongOrNull() })
        } else {
            CopyOnWriteArraySet()
        }

    private fun save() {
        chatListFile.printWriter().use { w ->
            for (qq in list) {
                w.println(qq)
            }
        }
    }

    suspend fun add(qq: Long): Boolean {
        mutex.withLock {
            return list.add(qq).also { if (it) save() }
        }
    }

    suspend fun remove(qq: Long): Boolean {
        mutex.withLock {
            return list.remove(qq).also { if (it) save() }
        }
    }

    operator fun contains(qq: Long): Boolean = list.contains(qq)
}


